const db = require('../db');
const { generateToken, verifyToken } = require('../config/auth');
const bcrypt = require('bcrypt');
// 查询用户是否存在
const checkUser = async (req, res) => {
  console.log("🚀 ~ checkUser ~ req:", req.body)
  const { userName } = req.body;
  // 验证输入
  if (!userName) {
    return res.status(400).json({ error: 'userName is required' });
  }

  // 检查用户名是否已存在
  const [existingUser] = await db.query('SELECT * FROM users WHERE userName = ?', [userName]);
  if (existingUser.length > 0) {
    return res.status(409).json({ error: '账号已存在' });
  }
};

// 账号注册
const register = async (req, res) => {
  const { userName, password } = req.body;

  // 验证输入
  if (!userName || !password) {
    return res.status(400).json({ error: 'userName and password are required' });
  }

  try {
    // 检查用户名是否已存在
    checkUser(req, res)

    // 加密密码
    const hashedPassword = await bcrypt.hash(password, 10);

    // 生成JWT令牌
    const token = generateToken({ userName });
    // 插入新用户到数据库
    const [insertResult] = await db.query('INSERT INTO users (userName, password,token) VALUES (?, ?,?)', [userName, hashedPassword, token]);
    const userId = insertResult.insertId;

    // 新建默认文件夹和回收站文件夹
    const folderNames = [`默认文件夹-${userId}`, `回收站-${userId}`];
    const folderIds = await Promise.all(folderNames.map(async (folderName) => {
      const [folderResult] = await db.query('INSERT INTO folders (name, userId) VALUES (?, ?)', [folderName, userId]);
      return folderResult.insertId;
    }));
    // 更新用户记录，添加文件夹ID
    await db.query('UPDATE users SET folderId = ?, recycleBinId = ? WHERE id = ?', [folderIds[0], folderIds[1], userId]);

    res.success({ data: '用户注册成功', token });
  } catch (error) {
    console.error('Error registering user:', error);
    res.status(500).json({ error: 'Failed to register user' });
  }
}
// 账号登录
const login = async (req, res) => {
  const { userName, password } = req.body;

  // 验证输入
  if (!userName || !password) {
    return res.status(400).json({ error: '请输入账号或密码' });
  }

  try {
    // 检查用户名是否存在
    const [existingUser] = await db.query('SELECT * FROM users WHERE userName = ?', [userName]);

    if (existingUser.length === 0) {
      return res.status(404).json({ error: '账号不存在' });
    }
    // 验证密码
    const passwordMatch = await bcrypt.compare(password, existingUser[0].password);

    if (!passwordMatch) {
      return res.status(401).json({ error: '密码不正确' });
    }
    // 生成新的 JWT 令牌
    const newToken = generateToken({ userName });

    // 更新数据库中用户的令牌值
    await db.query('UPDATE users SET token = ? WHERE userName = ?', [newToken, userName]);
    console.log('existingUser', existingUser)

    res.success({ data: existingUser });
  } catch (error) {
    console.error('Error logging in:', error);
    res.status(500).json({ error: '登录失败' });
  }
};
// 修改密码
const changePassword = async (req, res) => {
  const { userName, oldPassword, newPassword } = req.body;

  // 验证输入
  if (!userName || !oldPassword || !newPassword) {
    return res.status(400).json({ error: '请输入用户名、旧密码和新密码' });
  }

  try {
    // 检查用户名是否存在
    const [existingUser] = await db.query('SELECT * FROM users WHERE userName = ?', [userName]);

    if (existingUser.length === 0) {
      return res.status(404).json({ error: '账号不存在' });
    }

    // 验证旧密码
    const passwordMatch = await bcrypt.compare(oldPassword, existingUser[0].password);

    if (!passwordMatch) {
      return res.status(401).json({ error: '旧密码不正确' });
    }

    // 更新数据库中用户的密码
    const hashedNewPassword = await bcrypt.hash(newPassword, 10);
    await db.query('UPDATE users SET password = ? WHERE userName = ?', [hashedNewPassword, userName]);

    res.json({ message: '密码修改成功' });
  } catch (error) {
    console.error('Error changing password:', error);
    res.status(500).json({ error: '密码修改失败' });
  }
};

module.exports = {
  login, register, changePassword
}